package com.example.swimmingpool.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.example.swimmingpool.SwimmingPoolThreadLocal;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MybatisPlusColumnsHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        var userId = (String) SwimmingPoolThreadLocal.getUserId().toString();
        if (metaObject.getValue("createBy") == null) {
            this.strictInsertFill(metaObject, "createBy", String.class, userId);
        }
        if (metaObject.getValue("updateBy") == null) {
            this.strictInsertFill(metaObject, "updateBy", String.class, userId);
        }

        this.strictInsertFill(metaObject, "deleteFlag", Integer.class, 0);
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        if (metaObject.hasGetter("teachStatus")) {
            this.strictInsertFill(metaObject, "teachStatus", Integer.class, 0);
        }
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        var userId = (String) SwimmingPoolThreadLocal.getUserId().toString();
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        if (metaObject.getValue("updateBy") == null) {
            this.strictInsertFill(metaObject, "updateBy", String.class, userId);
        }

    }
}
